use axum::{
    extract::{Form, State},
    http::StatusCode,
    Json
};

use std::sync::Arc;
use tokio::sync::Mutex;

use crate::database::SqliteDb;

#[derive(serde::Deserialize)]
pub struct FormData { 
    pub email: String,
    pub name: String 
}

#[axum_macros::debug_handler]
pub async fn subscribe(State(db): State<Arc<Mutex<SqliteDb>>>, Form(form): Form<FormData>) -> (StatusCode, Json<String>) {
    let db = db.lock().await;
    match db.insert_subscription(&form).await{
        Ok(_) => (StatusCode::OK, Json("OK".to_string())),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(e.to_string()))
    }
}